package funcktion;

import tools.BookAddGUI;
import tools.BorrowGUI;
import tools.BookUpdateGUI;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

    public class    BookManage extends JFrame {
        private JTable bookTable;
        private BookTableModel tableModel;

    public BookManage() {
        // 设置窗口标题
        setTitle("图书管理系统");

        // 创建表格模型和表格对象
        tableModel = new BookTableModel();
        bookTable = new JTable(tableModel);

        // 创建滚动面板，将表格添加到滚动面板中
        JScrollPane scrollPane = new JScrollPane(bookTable);

        // 创建删除按钮和修改按钮
        JButton addButton = new JButton("增添");
        JButton deleteButton = new JButton("删除");
        JButton updateButton = new JButton("修改");


        // 添加按钮的点击事件监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = bookTable.getSelectedRow();
                if (selectedRow != -1) {
                    // 获取选中行的图书编号
                    String bookId = (String) tableModel.getValueAt(selectedRow, 0);
                    // 调用删除图书的方法
                    deleteBook(bookId);
                    // 刷新表格数据
                    refreshTableData();
                }else {
                    JOptionPane.showMessageDialog(null, "请选择一条数据", "警告", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = bookTable.getSelectedRow();
                //System.out.println(selectedRow);
                if (selectedRow != -1) {
                    setVisible(false);
                    // 获取选中行的图书编号
                    String bookId = (String) tableModel.getValueAt(selectedRow, 0);
                    BookUpdateGUI GUI = new BookUpdateGUI(bookId);
                    GUI.setVisible(true);
                }else {
                    JOptionPane.showMessageDialog(null, "请选择一条数据", "警告", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                BookAddGUI GUI = new BookAddGUI();
                GUI.setVisible(true);
            }
        });

        // 创建主面板，并设置布局
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板，并设置布局
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(addButton);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 将主面板添加到窗口中
        add(mainPanel);

        // 设置窗口大小和显示位置
        setSize(800, 400);
        setLocationRelativeTo(null);
//        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 刷新表格数据
        refreshTableData();
    }

    // 从数据库中查询图书数据，并刷新表格数据
    private void refreshTableData() {
        List<Book> books = queryBooksFromDatabase();
        tableModel.setBooks(books);
    }

    // 从数据库中查询图书数据
    private List<Book> queryBooksFromDatabase() {
        List<Book> books = new ArrayList<>();

        // 建立数据库连接
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "lang520520");
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM Book")) {

            // 遍历查询结果集，创建 Book 对象并添加到列表中
            while (rs.next()) {
                String bookId = rs.getString("bookId");
                String bookName = rs.getString("bookName");
                double price = rs.getDouble("price");
                int totalCopies = rs.getInt("totalCopies");
                int availableCopies = rs.getInt("availableCopies");
                String status = rs.getString("status");

                Book book = new Book(bookId, bookName, price, totalCopies, availableCopies, status);
                books.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return books;
    }

    // 删除图书
    private void deleteBook(String bookId) {

        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "lang520520");
            PreparedStatement stmt = conn.prepareStatement("DELETE FROM book WHERE bookId = ?")) {

            // 设置参数并执行删除操作
            stmt.setString(1, bookId);
            stmt.executeUpdate();
            JOptionPane.showMessageDialog(null, "删除成功", "操作成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 建立数据库连接
    }



    // 打开图书编辑对话框
    private void openUpdateBookDialog(String bookId) {
        // 根据图书编号查询数据库，获取图书信息
        // ...

        // 弹出对话框，显示图书信息和编辑表单
        // ...
    }

    // 内部类，表格模型
    private class BookTableModel extends AbstractTableModel {
        private List<Book> books;
        private String[] columnNames = {"图书编号", "图书名称", "价格", "总库存", "可借数量", "状态"};

        public void setBooks(List<Book> books) {
            this.books = books;
            fireTableDataChanged();
        }

        @Override
        public int getRowCount() {
            return books != null ? books.size() : 0;
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (books == null || rowIndex >= books.size()) {
                return null;
            }

            Book book = books.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return book.getBookId();
                case 1:
                    return book.getBookName();
                case 2:
                    return book.getPrice();
                case 3:
                    return book.getTotalCopies();
                case 4:
                    return book.getAvailableCopies();
                case 5:
                    return book.getStatus();
                default:
                    return null;
            }
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
    }

    // 内部类，图书类
    private class Book {
        private String bookId;
        private String bookName;
        private double price;
        private int totalCopies;
        private int availableCopies;
        private String status;

        public Book(String bookId, String bookName, double price, int totalCopies, int availableCopies, String status) {
            this.bookId = bookId;
            this.bookName = bookName;
            this.price = price;
            this.totalCopies = totalCopies;
            this.availableCopies = availableCopies;
            this.status = status;
        }

        public String getBookId() {
            return bookId;
        }

        public String getBookName() {
            return bookName;
        }

        public double getPrice() {
            return price;
        }

        public int getTotalCopies() {
            return totalCopies;
        }

        public int getAvailableCopies() {
            return availableCopies;
        }

        public String getStatus() {

            return status;
        }
    }
}

